package jmcnet.libcommun.socketpool
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.getQualifiedClassName;
	
	import jmcnet.libcommun.logger.JMCNetLog4JLogger;
	
	/**
	 * A timed socket is an extension of a socket. It store some date information : creation date and connexion date
	 */
	public class TimedSocket extends Socket
	{
		private static var log:JMCNetLog4JLogger = JMCNetLog4JLogger.getLogger(TimedSocket);
		
		private var _creationTime:Number=0;
		private var _connexionTime:Number=0;
		public var inUseTime:Number=0;
		public var releaseTime:Number=0;
		private var _id:uint=0;
		
		private static var socketId:uint=0;
		
		public function TimedSocket(host:String=null, port:int=0) {
			super(host, port);
			_id = socketId;
			socketId++;
			releaseTime = _creationTime = new Date().getTime();
			
			this.addEventListener(Event.CLOSE,onSocketClose);
			this.addEventListener(Event.CONNECT, onSocketOpen);
			this.addEventListener(IOErrorEvent.IO_ERROR,onSocketIoError);
			this.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSocketSecurityError);
			
		}

		public function get creationTime():Number {
			return _creationTime;
		}

		public function get connexionTime():Number {
			return _connexionTime;
		}
		
		private function onSocketClose(event:Event):void {
			if (SocketPool.logSocketPool) log.evt("TimedSocket : socket #"+_id+" has closed.");
			_connexionTime = 0;
		}
		
		private function onSocketOpen(event:Event):void {
			if (SocketPool.logSocketPool) log.evt("TimedSocket : socket #"+_id+" has opened.");
			_connexionTime = new Date().getTime();
		}
		
		private function onSocketIoError(event:IOErrorEvent):void {
			log.error("TimedSocket : socket #"+_id+" io error="+event.text);
			_connexionTime = 0;
		}
		
		private function onSocketSecurityError(event:SecurityErrorEvent):void {
			log.error("TimedSocket : socket #"+_id+" security error"+event.text);
			_connexionTime = 0;
		}

		public function get id():uint {	return _id;	}

	}
}